package com.moter.demo01.requirements;

import java.io.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 多线程读取IO如果某一现场读取超过一分钟自动中断
 */
public class Demo1 {
    static class Listen implements Runnable{
        private Thread father;

        public Listen(Thread father) {
            this.father = father;
        }

        @Override
        public void run() {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Thread.State state = father.getState();
                    if(state!= Thread.State.TERMINATED)//如果线程没有执行完毕
                        father.interrupt();
                }
            },6*1000);//6秒后执行这个任务
        }
    }
    public static void main(String[] args) {
        ReadWriteLock lock = new ReentrantReadWriteLock();
        //读锁
        Thread read = new Thread(() -> {
            lock.readLock().lock();
            try {
                System.out.println(Thread.currentThread().getName());
                read();

            } finally {
                lock.readLock().unlock();
            }
        });
        read.start();
        //写锁
        new Thread(() -> {
            lock.writeLock().lock();
            try {
                System.out.println(Thread.currentThread().getName());
                read();
            } finally {
                lock.writeLock().unlock();
            }
        }).start();
    }

    public static void read() {
        Thread thread = new Thread(new Listen(Thread.currentThread()));
        thread.setDaemon(true);
        thread.start();//执行线程
        Reader in = null;
        try {
            in = new FileReader("E:\\myCode\\JUC\\src\\main\\java\\com\\moter\\demo01\\alllocks\\deadlock\\Player.txt");
            int read;
            while ((read = in.read()) != -1) {
                char read1 = (char) read;
                TimeUnit.DAYS.sleep(1);
                System.out.print(read1);
            }
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
